package com.dayaokeji.rhythmschoolstudent.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;

import com.dayaokeji.rhythmschoolstudent.BuildConfig;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.service.AppUniqueIdService;
import com.litesuits.common.utils.AndroidUtil;
import com.orhanobut.logger.Logger;

import java.util.List;

/**
 * Created by Gorden on 2017/9/23.
 */

public class AndroidUtils {

    private static Handler handler;

    public final static String WIDTH = "width";

    public final static String HEIGHT = "height";


    /**
     * 根据pid得到进程名称
     * @param context
     * @param pid
     * @return
     */
    public static String getProcessName(Context context,int pid) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : runningAppProcesses) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public static boolean isProessRunning(Context context, String proessName) {

        boolean isRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();
        for(ActivityManager.RunningAppProcessInfo info : lists){
            if(info.processName.equals(proessName)){
                //Log.i("Service2进程", ""+info.processName);
                isRunning = true;
            }
        }

        return isRunning;
    }


    public static Handler getMainHandler() {
        if (handler == null) {
            handler = new Handler(Looper.getMainLooper());
        }
        return handler;
    }

    public static int dp2px(float dp) {
        DisplayMetrics displayMetrics = App.getAppContext().getResources().getDisplayMetrics();
        return (int) (displayMetrics.density * dp + 0.5f);
    }

    /**
     * px转dp
     *
     * @param px      the pixel value
     * @return value in dp
     */
    public static int px2dp(float px) {
        DisplayMetrics displayMetrics =  App.getAppContext().getResources().getDisplayMetrics();
        return (int) ((px / displayMetrics.density) + 0.5f);
    }

    /**
     * 得到当前APP版本名称
     * @return
     */
    public static String getVersionName() {
        return BuildConfig.VERSION_NAME;
    }

    public static void hideSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void hideSoftInput(Window window) {
        hideSoftInput(window.getDecorView());
    }

    public static String getMobileOnlyFlag(Context context) {
        final String androidId = getAndroidId(context);
        final String ethernetMacAddress = AndroidUtil.getMacAddress(context);
        final StringBuilder builder = new StringBuilder();
        builder.append(androidId);
        builder.append(ethernetMacAddress);
        if (TextUtils.isEmpty(builder.toString())) {
            if (AppUniqueIdService.Companion.getFileString() != null) {
                builder.append(AppUniqueIdService.Companion.getFileString());
            }
        }
        Logger.d("only flag = "+builder.toString());
        return MD5Util.md5(builder.toString());
    }

    /**
     * 获取 ANDROID_ID
     */
    public static String getAndroidId(Context context) {
        String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    /**
     * get current wifi mac address
     * @return
     */
    public static String connectWifiMacAddr() {
        final WifiManager wifiManager = (WifiManager) App.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null) {
            return TextUtils.isEmpty(connectionInfo.getBSSID())? null : connectionInfo.getBSSID().replace(":","").toUpperCase();
        }else {
            return null;
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * APP是否处于前台唤醒状态
     *
     * @return
     */
    public static boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) App.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = App.getAppContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public static boolean runningTopActivity() {
        ActivityManager am = (ActivityManager)  App.getAppContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            return topActivity.getPackageName().equals(App.getAppContext().getPackageName());
        }
        return false;
    }

    public static void exitApp() {
        Process.killProcess(Process.myPid());
        System.exit(0);
    }
}
